package controller.UserController;

import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppVariable;
import common.ResultAjax;
import services.UserService;
import services.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");
        HttpSession session = req.getSession(false);
        if(session==null){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"未登录，无需注销！"));
            resp.getWriter().write(respJson);
            return ;
        }
        if (session != null) {
            //注销session
            User user = (User) session.getAttribute(AppVariable.SESSION_USERINFO_KEY);
            session.invalidate();
        }
        String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(200,"注销成功！",null));
        resp.getWriter().write(respJson);
    }
}
